package com.gd.deron.smartrobot.baobao.service;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

import com.gd.deron.smartrobot.baobao.app.MyApplication;
import com.gd.deron.smartrobot.baobao.info.MusicNameInfo;
import com.gd.deron.smartrobot.baobao.info.OrderInfo;
import com.gd.deron.smartrobot.baobao.info.RobotInfo;
import com.gd.deron.smartrobot.baobao.utils.BlueTools;
import com.gd.deron.smartrobot.baobao.utils.Config;
import com.gd.deron.smartrobot.baobao.utils.InstructionUtil;
import com.gd.deron.smartrobot.baobao.utils.PlayMusicTool;

import android.R;
import android.annotation.SuppressLint;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.BluetoothAdapter.LeScanCallback;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

@SuppressLint("NewApi")
public class BluetoothBleService extends Service {
	private BLEBinder ibinder = new BLEBinder();
	private BluetoothManager mBluetoothManager = null;
	private BluetoothAdapter mBluetoothAdapter = null;
	public BluetoothGatt mBluetoothGatt = null;
	/**发送数据的特征值*/
	private BluetoothGattCharacteristic writeReadCh = null;
	private String bleAddress;
	private BluetoothDevice mBluetoothDevice = null;
	//public  String DEVICE_NAME = "FSRK-sample-001";//37
	//public  String DEVICE_NAME = "Deron-tibet";//36 //20:91:48:9E:4B:6B
	/**爱佳二代西藏版单片机的蓝牙服务UUID*/
	public String SERVICE_UUID = "0000fff0-0000-1000-8000-00805f9b34fb";
	/**爱佳二代西藏版单片机蓝牙可读可写可通知特征值UUID*/
	public  String WRITE_READ_CHARA  = "0000fff6-0000-1000-8000-00805f9b34fb";
	/**用来激活蓝牙通知属性的UUID*/
	public  String CHARACTERISTIC_UUID_RETURN = "00002901-0000-1000-8000-00805f9b34fb";

	
	protected static final String TAG = "单片机蓝牙服务";
	private Timer timer;
    private TimerTask timerTask;
	
	Handler mHandler = new Handler();
	
	private int count=0;

	BluetoothGattCallback mGattcallback = new BluetoothGattCallback() {
		/**连接状态*/
		public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
			Log.e(TAG,"连接状态"+"status=" + status + "  newState=" + newState);
			if (newState == BluetoothProfile.STATE_CONNECTED) {
				//if (gatt.getDevice().getName().equals(DEVICE_NAME)) {
					Log.e(TAG,"连接成功..");
					MyApplication.isConnect = true;//标识为true
					
				//}
				Log.e("服务","发现服务 ： " + gatt.discoverServices());
			} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
				Log.e(TAG,"连接失败..");
				broadcastSend(Config.DISCONNECTED);
				MyApplication.isConnect = false;
				startTimer();//断线开启搜索定时器
			}
		};
		
		/**发现新服务以及特征值*/
		public void onServicesDiscovered(BluetoothGatt gatt, int status) {
			Log.e(TAG,"发现新服务以及特征值"+"status=" + status );
			if (status == BluetoothGatt.GATT_SUCCESS) {
				//遍历服务，获取服务UUID
				List<BluetoothGattService> serverList = gatt.getServices();
				for (BluetoothGattService server : serverList) {
					System.out.println("==ser:" + server.getUuid());
				}
				//先用服务的uuid找到该服务
				BluetoothGattService service = gatt.getService(UUID.fromString(SERVICE_UUID));
				//获取该服务的特征值
				List<BluetoothGattCharacteristic> CHlist = service.getCharacteristics();
				for (BluetoothGattCharacteristic ch : CHlist) {
					if(ch.getUuid().toString().equals(WRITE_READ_CHARA)){
						writeReadCh = ch;
						if (writeReadCh != null) {
							final int charaProp = writeReadCh.getProperties();
							if ((charaProp & BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
								mBluetoothGatt.setCharacteristicNotification(ch, true);
								BluetoothGattDescriptor descriptor = ch.getDescriptor(UUID.fromString(CHARACTERISTIC_UUID_RETURN));
								if (descriptor != null) {
									descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
									mBluetoothGatt.writeDescriptor(descriptor);
									Log.e("========",ch.getUuid() + "===激活通知属性： " + mBluetoothGatt.writeDescriptor(descriptor));
								}
							}else{
								Log.e("=====","不具有通知属性");
							}
							broadcastSend(Config.CON_SUCCESS);
						}
					}
				}
			}
		};
		
		
		/**监听发出去的数据*/
		public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
			//Log.e(TAG, "主动发出去的数据=" + BlueTools.bytesToHexString(characteristic.getValue()) + ";status:"+status);
		};
		
		/**监听蓝牙主动发给app的数据(需要先激活该特征值)(读取密码验证信息)*/
		public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
			String codeString = BlueTools.bytesToHexString(characteristic.getValue());
			Log.e(TAG, codeString);
			
			if(codeString.startsWith("AABBCC")){
				switch (codeString) {
				case OrderInfo.STASR_ASR://收到开始语音指令。开始对话
					broadcastSend(Config.START_ASR);
					break;
				case OrderInfo.STASR_ASR_UP://松开手
					broadcastSend(Config.STOP_ASR);
					break;
				case OrderInfo.STASR_ASR_COPY://收到开始语音指令。开始对话
					broadcastSend(Config.START_ASR_COPY);
					break;
				case OrderInfo.STASR_ASR_UP_COPY://松开手
					broadcastSend(Config.STOP_ASR_COPY);
					break;
				case OrderInfo.VOICE://松开手
					broadcastSend(Config.VOICE);
					break;
				case OrderInfo.TOUCH_DOWN://触摸按下
					broadcastSend(Config.TOUCH_DOWN);
					break;
				case OrderInfo.TOUCH_UP://触摸松开
					broadcastSend(Config.TOUCH_UP);
					break;
				default:
					break;
				}
			}else if(codeString.startsWith("AABBEE")){
				if(codeString.equals(MusicNameInfo.MUSIC_STOP)){
					PlayMusicTool.close();
				}else{
					try {
						int data = Integer.parseInt(codeString.substring(8, 10 ), 16)-1;
						PlayMusicTool.getInstance().playMusicToTitle(MusicNameInfo.MUSIC_ARR[data], getApplicationContext(), "song");
						Log.e(TAG, MusicNameInfo.MUSIC_ARR[data]);
					} catch (Exception e) {
					}
				}
				
			}else if(codeString.startsWith("AABBFF")){//语音合成
				
				try {
					int data = Integer.parseInt(codeString.substring(8, 10 ), 16);
					MyApplication.ASR = MusicNameInfo.PLAY_TTS_ARR[data];
					Log.e(TAG, MusicNameInfo.PLAY_TTS_ARR[data]);
					broadcastSend(Config.ASR_ANSWER );
				} catch (Exception e) {
				}
				
			}else if(codeString.equals(InstructionUtil.CLEAR_DATA)){//清除本地语音录入数据库
				broadcastSend(Config.CLEAR_ARS_SQL);
			}else if(codeString.equals(InstructionUtil.WAKE_ROBOT_OFFLINE)){//一键唤醒离线
				broadcastSend(Config.WAKE_ROBOT_OFFLINE);
			}else if(codeString.equals(InstructionUtil.WAKE_ROBOT_ONLINE)){//一键唤醒在线
				broadcastSend(Config.WAKE_ROBOT_ONLINE);
			}else{
				if(codeString.startsWith("AA")&&codeString.endsWith("AA"))//不是AA开头和结尾的字符，我们认为是提问和回答的字符、否则不作处理
					return;//直接 
				String code = null;
				try {
					code = new String(characteristic.getValue(),"GB2312");
					MyApplication.ANSWERANDQUESTION = code;
					Log.e(TAG, ">>>>>>>>>>>>"+code);
					//if(code.startsWith("hello:")){//
						//broadcastSend(Config.PLAY_TTS);
					//}else{
						broadcastSend(Config.SUBMIT_QUESTION_ANSWER);
					//}
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}
		}

		private void startToActivity(Class class1) {
			Intent intent = new Intent(BluetoothBleService.this, class1);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intent);
		};
		
		/**当手机向蓝牙请求数据时，监听返回的数据(读取电量信息等)*/
		public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
			Log.e(TAG, "手机向蓝牙请求数据="+ BlueTools.bytesToHexString(characteristic.getValue()));
		};
	};

	/**初始化*/
	public boolean initialize() {
		//初始化蓝牙适配器
		if (mBluetoothManager == null) {
			mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
			if (mBluetoothManager == null) {
				return false;
			}
		}
		
		if (mBluetoothAdapter == null) {
			mBluetoothAdapter = mBluetoothManager.getAdapter();
			if (mBluetoothAdapter == null) {
				return false;
			}
		}
		MyApplication.mBluetoothAdapter = mBluetoothAdapter;
		//蓝牙关闭状态，自动打开蓝牙
		if (!MyApplication.mBluetoothAdapter.isEnabled()) {
			MyApplication.mBluetoothAdapter.enable();
		}
		return true;
	}

	// 打开蓝牙
	public void openBluetooth() {
		if (!mBluetoothAdapter.isEnabled()) {
			mBluetoothAdapter.enable();
		}
	}

	// 根据Max 地址链接蓝牙
	public boolean connect(String address) {
		if (mBluetoothAdapter == null) 
			return false;
		if (bleAddress != null && address.equals(bleAddress)
				&& mBluetoothGatt != null) {
			if (mBluetoothGatt.connect()) 
				return true;
			else 
				return false;
		}
		mBluetoothDevice = mBluetoothAdapter.getRemoteDevice(address);
		if (mBluetoothDevice == null) 
			return false;
		mBluetoothGatt = mBluetoothDevice.connectGatt(this, false, mGattcallback);
		bleAddress = address;
		return true;
	}


	/**发送数据*/
	public void sendData(String data) {
		if(MyApplication.isConnect){
			if (mBluetoothGatt != null && writeReadCh != null) {
				boolean flag = writeCharacteristic(writeReadCh,BlueTools.hexStringToBytes(data));
				Log.e("BluetoothBleService", "发送数据》》》》》》》》》》》》》》》》");
			}
		}else{
			Log.e("BluetoothBleService", "设备未连接");
		}
	}

	/** 手动断开蓝牙连接 */
	public void disconnect() {
		if (mBluetoothAdapter == null || mBluetoothGatt == null) {
			return;
		}
		if (mBluetoothGatt != null) {
			mBluetoothGatt.disconnect();
			mBluetoothGatt.close();
			mBluetoothGatt = null;
			broadcastSend(Config.SHOUDONG_DUANKAI);
			MyApplication.isConnect = false;
		}
	}
	
	/**5秒搜索蓝牙*/ 
	@SuppressWarnings("deprecation")
	public void ScanBLE(boolean able) {
		if (able) {
			MyApplication.mBluetoothAdapter.startLeScan(mLeCallback);
			mHandler.postDelayed(new Runnable() {
				@Override
				public void run() {
					MyApplication.mBluetoothAdapter.stopLeScan(mLeCallback);
				}
			}, 4 * 1000);
		} else {
			MyApplication.mBluetoothAdapter.stopLeScan(mLeCallback);
		}
	}
		
	/**扫描指定类型的外围设备*/
	@SuppressLint("NewApi")
	private BluetoothAdapter.LeScanCallback mLeCallback = new LeScanCallback() {
		@Override
		public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
			
			String address= device.getAddress();
			if (address!=null ) {
				if(RobotInfo.ROBOT_BLUEADARESS!=null&&RobotInfo.ROBOT_BLUEADARESS.equals(address)){
					MyApplication.myDevice = device;
					MyApplication.device_address = device.getAddress();
					stopTimer();//连接停止搜索定时器
					broadcastSend(Config.FIND_DEVICE);
				}
			}
		}
	};
	/**扫描和显示可以提供的蓝牙设备*/
	public void startTimer() {
		openBluetooth();
        stopTimer();
        if (timer == null) {
            timer = new Timer();
        }
        if (timerTask == null) {
            timerTask = new TimerTask() {
                @SuppressWarnings("deprecation")
				@Override
                public void run() {
                	count++;
                	 if(count>=2){
                		 count = 0;
                		 disconnect();
                	 }
                	MyApplication.myDevice = null;
                    mBluetoothAdapter.startLeScan(mLeCallback);
                    try {
                        Thread.sleep(4500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    mBluetoothAdapter.stopLeScan(mLeCallback);
                }
            };
        }
        if (timer != null && timerTask != null) {
            timer.schedule(timerTask, 500, 5000);//0.5秒开始执行，每5秒执行一次
        }
    }
	/**停止扫描*/
	@SuppressWarnings("deprecation")
	public void stopTimer() {
		mBluetoothAdapter.stopLeScan(mLeCallback);
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }
    }
	
	/**设置设备可读可写UUID*/
	public void setWRITE_READ_CHARA(String wRITE_CHARA) {
		WRITE_READ_CHARA = wRITE_CHARA;
	}

	/**读数据*/
	public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return;
        }
        mBluetoothGatt.readCharacteristic(characteristic);
    }
	/**写入数据*/
    public boolean writeCharacteristic(BluetoothGattCharacteristic characteristic,byte[]test){
    	boolean flag = false;  		
	    characteristic.setValue(test);
	    flag=mBluetoothGatt.writeCharacteristic(characteristic);
		return flag;    	
   }
    /**设置当指定characteristic值变化时，发出通知*/
//	public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,
//            boolean enabled) {
//		if (mBluetoothAdapter == null || mBluetoothGatt == null) {
//		Log.e(TAG, "BluetoothAdapter not initialized");
//		return;
//		}
//		mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
//		List<BluetoothGattDescriptor> descriptors=characteristic.getDescriptors();
//		for(BluetoothGattDescriptor dp:descriptors){
//		dp.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
//		mBluetoothGatt.writeDescriptor(dp);
//		}
//	}
	/**根据服务UUID获取服务*/
//	 public BluetoothGattService getSupportedGattServices(UUID uuid) {
//	    	BluetoothGattService mBluetoothGattService;
//	    	if (mBluetoothGatt == null) return null;
//	    	mBluetoothGattService=mBluetoothGatt.getService(uuid);
//	        return mBluetoothGattService;
//	    }  
	@Override
	public IBinder onBind(Intent intent) {
		return ibinder;
	}
	/**获取类对象*/
	public class BLEBinder extends Binder {
		public BluetoothBleService getService() {
			return BluetoothBleService.this;
		}
	}
	/**发送广播*/
	private void broadcastSend(final String action) {
		final Intent inte = new Intent(action);
		sendBroadcast(inte);
	}
	/**发送带数据的广播*/
	private void broadcastSend(final String action,String order) {
		final Intent inte = new Intent(action);
		inte.putExtra("data", order);
		sendBroadcast(inte);
	}
	public void close() {
	    if (mBluetoothGatt == null) {
	        return;
	    }
	    mBluetoothGatt.close();
	    mBluetoothGatt = null;
	}
}
